package info.rflow.actions;

import info.rflow.Utils;
import info.rflow.model.RBlock;
import info.rflow.preferences.GeneralSettings;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;


/**
 * Document me!
 *
 * @author Holger Brandl
 */
public class OpenCurrentBlockInEditor extends AbstractAction {

    private RBlock rBlock;


    public OpenCurrentBlockInEditor(RBlock rBlock) {
        this.rBlock = rBlock;

        putValue(NAME, "Open in Texteditor");
//        putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.ALT_MASK));
    }


    public void actionPerformed(ActionEvent e) {
        File rFile = rBlock.getWorkflowModel().getRFile();
        int lineNumber = rBlock.getWorkflowModel().getLineNumber(rBlock);

        try {
            String editorCmdPattern = Utils.getPrefs().get(GeneralSettings.NAV2BLOCK_CMD, GeneralSettings.NAV2BLOCK_CMD_DEFAULT);

            // replace the line-number placeholder
            String[] splitCmdPattern = editorCmdPattern.replace("$linenumber$", lineNumber + "").split(" ");

            // replace the file-name placeholder
            for (int i = 0; i < splitCmdPattern.length; i++) {
                if (splitCmdPattern[i].equals("$file$")) {
                    splitCmdPattern[i] = rFile.getAbsolutePath();
                }
            }

            Process proc = Runtime.getRuntime().exec(splitCmdPattern);
//                    new String[]{"/usr/local/bin/idea", "--line", lineNumber + "", rFile.getAbsolutePath()});
            proc.waitFor();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }


    }
}